package com.ithao.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ithao.dao.CourseDao;
import com.ithao.database.MmDaoException;
import com.ithao.entity.PageResult;
import com.ithao.entity.QueryPageBean;
import com.ithao.pojo.Course;
import com.ithao.service.CourseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @description ：学科业务实现类
 * @version: 1.0
 */
@Slf4j
@Service
@Transactional
public class CourseServiceImpl implements CourseService{
    @Autowired
    private CourseDao courseDao;

    @Override
    public void addCourse(Course course) {
        log.info("addCourse... course:{}", course);
        Integer result = courseDao.addCourse(course);
        log.info("result:{}", result);
        if (result == 0) {
            throw new MmDaoException("添加学科失败");
        }
    }

    @Override
    public PageResult findListByPage(QueryPageBean queryPageBean) {
        log.info("findListByPage:{}", queryPageBean);
        //开启分页插件
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        // (根据条件)获取分页数据集
        Page<Course> page = courseDao.selectListByPage(queryPageBean.getQueryParams());
        //List<Course> courseList = courseDao.selectListByPage(queryPageBean);
        List<Course> courseList = page.getResult();
        long totalCount = page.getTotal();
        log.info("findListByPage courseList:{} ,totalCount:{} ", courseList,totalCount);
        // 获取记录总数
        return new PageResult(totalCount, courseList);
    }

    @Override
    public void updateCourse(Course course) {
        log.info("updateCourse... course:{}", course);
        Integer result = courseDao.updateCourse(course);
        if (result == 0) {
            throw new MmDaoException("更新学科失败，Id不存在");
        }
    }

    @Override
    public void deleteCourse(Integer id) {
        Long cataLogQty = courseDao.selectCountCatalogById(id);
        Long tagQty = courseDao.selectCountTagById(id);
        if (cataLogQty > 0 || tagQty > 0) {
            throw new MmDaoException("学科下有数据，不能删除学科数据");
        }
        Integer result = courseDao.deleteCourse(id);
        if (result == 0) {
            throw new MmDaoException("删除学科失败");
        }
    }

    @Override
    public List<Course> findListAll() {
        return courseDao.selectListAll();
    }
}
